/**
 * ResponseScriptAPIReceiver.java
 * ************************** 
 * @date May 18, 2011
 * @author Michele Tamburini
 * 
 * **************************
 */
package infrastructureAPI.backendGate.scriptsResponse;

import infrastructureAPI.APIMessages.ResponseMessage;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.rmi.NoSuchObjectException;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;

/**
 * Description: 
 *
 */
public class ConcreteResponseReceiverScriptAPI extends ResponseScriptAPIRemoteReceiver 
		implements ResponseReceiverScriptAPI{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	/**
	 * @param address
	 * @param registrationName
	 * @throws UnknownHostException
	 * @throws RemoteException
	 */
	public ConcreteResponseReceiverScriptAPI(InetAddress address,
			String registrationName) throws UnknownHostException,
			RemoteException {
		super(address, registrationName);
//		this.registrationName = registrationName;
//		this.registrationAddress = address;
//		receivedMessages = new ArrayDeque<ResponseMessage>();
//		responseReceiver = new ResponseScriptAPIRemoteReceiver();
//		registryToRmiregistry(address , registrationName);
	}

	@Override
	public ResponseMessage waitForResponseMessage(){
		ResponseMessage msg = null;
		
		if(!receivedMessages.isEmpty()){
			synchronized (receivedMessages) {
				msg = receivedMessages.poll();
			}
			
		}else{
			while(msg == null){
				try {
					synchronized (receivedMessages) {
						receivedMessages.wait(0);
						if(!receivedMessages.isEmpty())
							msg = receivedMessages.poll();
					}
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
		return msg;
	}
	
	public boolean deRegisterAPIReceiver()throws RemoteException{
		boolean ret = false;
		try {
			UnicastRemoteObject.unexportObject(responseReceiver, true);
			Registry registry = LocateRegistry.getRegistry(registrationAddress.getHostAddress());
			registry.unbind(registrationName);
			ret = true;
		} catch (NoSuchObjectException e) {
			e.printStackTrace();		
		} catch (NotBoundException e) {
			e.printStackTrace();
		}
		return ret;
	}

	@Override
	public boolean terminate(){
		boolean ret = false;
		try {
			ret = deRegisterAPIReceiver();
		} catch (RemoteException e) {
			e.printStackTrace();
		}
		return ret;
	}

	@Override
	public boolean initializeAndConnect(){
		// TODO Auto-generated method stub
		return false;
	}

	
}
